<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{title}}</title>
    <link rel="stylesheet" href="/css/bootstrap.css">
    <link rel="stylesheet" href="/css/quick_layout.css">
    <script src="/js/jquery.js"></script>
</head>
<body>
<div class="mt20 mb20 tc">
    <button type="button" name="button" class="btn btn-default" onclick="auth()">获取token</button>
</div>
<div class="mt20 mb20 tc">
    <button type="button" name="button" class="btn btn-primary" onclick="getUser()">获取用户信息</button>
</div>
<div class="mt20 mb20 tc">
    <button type="button" name="button" class="btn btn-primary" onclick="destroyToken()">销毁token</button>
</div>
<script type="text/javascript">
    function auth() {
        $.ajax({
            url: 'http://localhost:3000/api/auth',
            type: 'GET',
            dataType: 'json',
            data: {
                username: 'jim',
                password: 'jim'
            },
            success: function (res) {
                if (res.code == 200) {
                    localStorage.setItem('token', res.token);
                } else {
                    console.log(JSON.stringify(res));
                }
            }
        });
    }

    function getUser() {
        var token = localStorage.getItem('token');
        if(!token) {
            alert('请先登录');
            return;
        }
        $.ajax({
            url: 'http://localhost:3000/api/getUser',
            type: 'GET',
            dataType: 'json',
            headers: {
                'Authorization': 'Bearer ' + token
            },
            success: function (res) {
                if (res.code == 200) {
                    console.log(res.data);
                    localStorage.setItem('token', res.token);
                } else if(res.code == 304) {
                    alert('请先登录');
                }
            }
        });
    }

    function destroyToken() {
        localStorage.removeItem('token');
        location.reload();
    }
</script>
</body>
</html>
